package com.zjw.service.message;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;

public class MessageParser {

    public static Message fromInputStream(InputStream inputStream) {
        try {
            return fromByte(inputStream.readAllBytes());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static Message fromByte(byte[] bytes) {
        ByteBuffer wrap = ByteBuffer.wrap(bytes);
        long messageId = wrap.getLong();
        long fromId = wrap.getLong();
        long toId = wrap.getLong();
        long time = wrap.getLong();
        int type = wrap.getInt();
        Message message = new Message();
        message.setMessageId(messageId);
        message.setFromId(fromId);
        message.setToId(toId);
        message.setTime(time);
        message.setType(type);
        if (bytes.length > 36) {
            byte[] content = new byte[bytes.length - 36];
            for (int i = 0; i < content.length; i++) {
                content[i] = wrap.get();
            }
            message.setBytes(content);
        }
        return message;
    }

    public static byte[] toByte(Message message) {
        byte[] content = message.getBytes();
        ByteBuffer buffer = ByteBuffer.allocate(36 + (content == null ? 0 : content.length));
        buffer.putLong(message.getMessageId());
        buffer.putLong(message.getFromId());
        buffer.putLong(message.getToId());
        buffer.putLong(message.getTime());
        buffer.putInt(message.getType());
        if (content != null) {
            buffer.put(content);
        }
        return buffer.array();
    }
}
